﻿using CTM.Web.Utils;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace CTM.Web.Filters
{
    public class ApplicationAuthorizeAttribute : AuthorizeAttribute
    {
        #region Fields

        private string _permission;
        private string[] _permissionSplit = new string[0];

        public string Permissions
        {
            get
            {
                return this._permission ?? string.Empty;
            }

            set
            {
                this._permission = value;
                this._permissionSplit = SplitString(value);
            }
        }

        #endregion

        #region Methods

        internal static string[] SplitString(string original)
        {
            if (string.IsNullOrEmpty(original))
            {
                return new string[0];
            }

            IEnumerable<string> split = from piece in original.Split(',')
                                        let trimmed = piece.Trim()
                                        where !string.IsNullOrEmpty(trimmed)
                                        select trimmed;
            return split.ToArray();
        }

        #endregion

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAuthorized = base.AuthorizeCore(httpContext);
            if (!isAuthorized || GlobalVariables.CurrentUser == null)
                return false;

            //IList<CTM.Web.Models.Input.ApplicationRole> roles = null;

            //if(GlobalVariables.CurrentUserRoles == null)
            //{
            //    var manager = httpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
            //    var roleManager = httpContext.GetOwinContext().Get<ApplicationRoleManager>();

            //    var roleNames = manager.GetRoles(GlobalVariables.CurrentUser.Id);
            //    roles = roleManager.Roles.Where(x => roleNames.Contains(x.Name)).ToList();
            //    GlobalVariables.CurrentUserRoles = roles;
            //}
            //else
            //    roles = GlobalVariables.CurrentUserRoles;

            //foreach (var role in roles)
            //{
            //    var permission = role.Permissions.FirstOrDefault(x => _permissionSplit.Contains(x.Code));
            //    if (permission != null)
            //        return true;
            //}
            //return false;
            return true;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                this.HandleUnAuthenticatedRequest(filterContext);
            }
            else
            {
                if (filterContext.HttpContext.Session["CURRENT_USER"] == null)
                {
                    filterContext.Result = new RedirectToRouteResult(
                            new RouteValueDictionary(
                                new
                                {
                                    controller = "Account",
                                    action = "Login",
                                    returnUrl = filterContext.HttpContext.Request.Url.PathAndQuery
                                })
                            );
                    return;
                }

                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    var js = new
                    {
                        success = false,
                        message = "You do not have permission to perform this action!"
                    };
                    filterContext.Result = new JsonResult { Data = js };
                }
                else
                {
                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new
                            {
                                controller = "Account",
                                action = "Unauthorized"
                            })
                        );
                }
            }
        }

        private void HandleUnAuthenticatedRequest(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                var js = new
                {
                    success = false,
                    message = "You must login to perform this action."
                };
                filterContext.Result = new JsonResult { Data = js };
            }
            else
            {
                var authenticationType = filterContext.HttpContext.User.Identity.AuthenticationType;
                if (!string.IsNullOrEmpty(authenticationType) && authenticationType != "Forms")
                {
                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new
                            {
                                controller = "Account",
                                action = "Unauthorized"
                            })
                        );
                }
                else
                {
                    filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new
                            {
                                controller = "Account",
                                action = "Login",
                                returnUrl = filterContext.HttpContext.Request.Url.PathAndQuery
                            })
                        );
                }
            }
        }
    }
}